layui.use(['table', 'form'], function () {
    //获取iframe的body元素
    var body = document.body
    var form = layui.form;

    var table = layui.table;
    form.on('select(search)', function (obj) {
        $(".searchTable .layui-btn").click();
    })
    table.render({
        elem: '#positionList',
        url: '/position/list',
        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        method: "get",
        request: {
            pageName: 'page', //页码的参数名称，默认：page
            limitName: 'limit' //每页数据量的参数名，默认：limit
        },
        parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": 0, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.data.totalCount, //解析数据长度
                "data": res.data.list //解析数据列表
            }
        },
        cellMinWidth: 80,//全局定义常规单元格的最小宽度，layui 2.2.1 新增
        where: {
            departmentUid: null,
            positionUid: null,
            status: null
        },
        page: true,
        loading: true,
        limit: 10,
        limits: [10, 20, 30],
        text: {
            none: '暂无相关数据！'//默认无数据
        },
        cols: [
            [{
                type: 'checkbox',
                fixed: 'left'
            }, {
                field: 'name',
                align: 'center',
                title: '职位名称',
            }, {
                field: 'person',
                align: 'center',
                title: '拥有可用人数',
            }, {
                field: 'createTime',
                align: 'center',
                title: '创建时间'
            }, {
                field: 'updateTime',
                align: 'center',
                title: '更新时间'
            }
            // , {
            //     fixed: 'right',
            //     title: '操作',
            //     toolbar: '#barDemo'
            // }
            ]
        ]
    });

    var $ = layui.$, active = {
        reload: function () {
            //查询条件组装
            var queryWhere = {};
            queryWhere['status'] = $("#status").find("option:selected").val();
            //执行重载
            table.reload('positionList', {
                page: {
                    curr: 1 //重新从第 1 页开始
                }
                , where: queryWhere
                , done: function (res, curr, count) {
                    this.where = queryWhere;
                }
            }, 'data');
            var value = $(body).find("#status").val()
            if (value == 0) {
                $(body).find("#delBtn")[0].style.display = "none"
                $(body).find("#isTBtn")[0].style.display = "inline-block"
                $(body).find("#cDeleteBtn")[0].style.display = "inline-block"
            } else if (value == 1) {
                $(body).find("#delBtn")[0].style.display = "inline-block"
                $(body).find("#isTBtn")[0].style.display = "none"
                $(body).find("#cDeleteBtn")[0].style.display = "none"
            }
        },
        getCheckData: function () { //获取选中数据
            var checkStatus = table.checkStatus('positionList')
                , data = checkStatus.data;
            layer.alert(JSON.stringify(data));
        }
        , getCheckLength: function () { //获取选中数目
            var checkStatus = table.checkStatus('positionList')
                , data = checkStatus.data;
            layer.msg('选中了：' + data.length + ' 个');
        }
        , isAll: function () { //验证是否全选
            var checkStatus = table.checkStatus('positionList');
            layer.msg(checkStatus.isAll ? '全选' : '未全选')
        }
    };

    $('.searchTable .layui-btn').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    //头部工具栏
    table.on('toolbar(positionList)', function (obj) {
        switch (obj.event) {
            case 'add': {
                document.getElementById("commentForm").reset();
                form.render();
                $(body).find("#uid").val("");
                var addOpen = layer.open({
                    //基本层类型
                    type: 1,
                    shadeClose: false,
                    scrollbar: false,
                    area: ['530px', '225px'],
                    //标题
                    title: '创建新职位',
                    //内容
                    content: $('#commentForm'),
                    //按钮
                    btn: ['创建', '取消'],
                    //确定按钮
                    yes: () => {
                        if (validateCode()) {
                            //开启loading
                            const loading = layer.load(2);
                            //获取表单内的所有值
                            var formObj = form.val('positionForm');
                            //发送数据到接口
                            $.ajax({
                                url: '/position/save',
                                method: "post",
                                contentType: 'application/json;charset=utf-8',
                                data: JSON.stringify(formObj),
                                dataType: "json",
                                success: function (data) {
                                    layer.close(loading);
                                    if (data.code == 200) {
                                        layer.alert("创建成功");
                                        layer.close(addOpen)
                                        $(".searchTable .layui-btn").click();
                                    } else {
                                        layer.alert(data.msg);
                                    }
                                }
                            });
                        }
                    },
                });
            }
                break;
            case 'delete': {
                layer.confirm('真的删除么？(将移入不可用职位)', function (index) {
                    //开启loading
                    const loading = layer.load(2);
                    var paramBody = [], count = 0;
                    var checkStatus = table.checkStatus('positionList')
                        , data = checkStatus.data;
                    data.forEach(function (i) {
                        paramBody[count++] = i.uid
                    })
                    $.ajax({
                        url: '/position/delete',
                        method: "post",
                        contentType: 'application/json;charset=utf-8',
                        data: JSON.stringify(paramBody),
                        dataType: "json",
                        success: function (res) {
                            layer.close(loading);
                            if (res.code == 200) {
                                layer.alert("删除成功!");
                                $(".searchTable .layui-btn").click();
                            } else {
                                layer.alert(res.msg);
                            }
                        }
                    });
                    layer.close(index);
                });
            }
                break;
            case 'isTAll': {
                layer.confirm('确定恢复么？(将移入可用职位)', function (index) {
                    //开启loading
                    const loading = layer.load(2);
                    var paramBody = [], count = 0;
                    var checkStatus = table.checkStatus('positionList')
                        , data = checkStatus.data;
                    data.forEach(function (i) {
                        paramBody[count++] = i.uid
                    })
                    $.ajax({
                        url: '/position/isT',
                        method: "post",
                        contentType: 'application/json;charset=utf-8',
                        data: JSON.stringify(paramBody),
                        dataType: "json",
                        success: function (res) {
                            layer.close(loading);
                            if (res.code == 200) {
                                layer.alert("成功!");
                                $(".searchTable .layui-btn").click();
                            } else {
                                layer.alert(res.msg);
                            }
                        }
                    });
                    layer.close(index);
                });
            }
                break;
            case 'cDelete': {
                layer.confirm('确定彻底删除么？(将删除这些职位以及其下的所有账号)', function (index) {
                    //开启loading
                    const loading = layer.load(2);
                    var paramBody = [], count = 0;
                    var checkStatus = table.checkStatus('positionList')
                        , data = checkStatus.data;
                    data.forEach(function (i) {
                        paramBody[count++] = i.uid
                    })
                    $.ajax({
                        url: '/position/cDelete',
                        method: "post",
                        contentType: 'application/json;charset=utf-8',
                        data: JSON.stringify(paramBody),
                        dataType: "json",
                        success: function (res) {
                            layer.close(loading);
                            if (res.code == 200) {
                                layer.alert("成功!");
                                $(".searchTable .layui-btn").click();
                            } else {
                                layer.alert(res.msg);
                            }
                        }
                    });
                    layer.close(index);
                });
            }
                break;
        }
    });

    //监听工具条
    table.on('tool(positionList)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            layer.confirm('真的删除么？(将移入不可用职位)', function (index) {
                //开启loading
                const loading = layer.load(2);
                var paramBody = []
                paramBody[0] = data.uid;
                $.ajax({
                    url: '/position/delete',
                    method: "post",
                    contentType: 'application/json;charset=utf-8',
                    data: JSON.stringify(paramBody),
                    dataType: "json",
                    success: function (res) {
                        layer.close(loading);
                        if (res.code == 200) {
                            layer.alert("删除成功!");
                            obj.del();
                        } else {
                            layer.alert(res.msg);
                        }
                    }
                });
                layer.close(index);
            });
        } else if (obj.event === 'edit') {
            var formObj = JSON.stringify(data);
            var formJson = JSON.parse(formObj)
            form.val('positionForm', formJson);
            var editOpen = layer.open({
                //基本层类型
                type: 1,
                shadeClose: false,
                scrollbar: false,
                area: ['530px', '225px'],
                //标题
                title: '编辑职位',
                //内容
                content: $('#commentForm'),
                //按钮
                btn: ['修改', '取消'],
                //确定按钮
                yes: () => {
                    if (validateCode()) {
                        //开启loading
                        const loading = layer.load(2);
                        //获取表单内的所有值
                        var formObj = form.val('positionForm');
                        //发送数据到接口
                        $.ajax({
                            url: '/position/update',
                            method: "post",
                            contentType: 'application/json;charset=utf-8',
                            data: JSON.stringify(formObj),
                            dataType: "json",
                            success: function (data) {
                                layer.close(loading);
                                if (data.code == 200) {
                                    layer.alert("修改成功!");
                                    layer.close(editOpen)
                                    $(".searchTable .layui-btn").click();
                                } else {
                                    layer.alert(data.msg);
                                }
                            }
                        });
                    }
                },
            });
        } else if (obj.event === 'isT') {
            layer.confirm('确定恢复么？(将移入可用职位)', function (index) {
                //开启loading
                const loading = layer.load(2);
                var paramBody = []
                paramBody[0] = data.uid;
                $.ajax({
                    url: '/position/isT',
                    method: "post",
                    contentType: 'application/json;charset=utf-8',
                    data: JSON.stringify(paramBody),
                    dataType: "json",
                    success: function (res) {
                        layer.close(loading);
                        if (res.code == 200) {
                            layer.alert("成功!");
                            obj.del();
                        } else {
                            layer.alert(res.msg);
                        }
                    }
                });
                layer.close(index);
            });
        } else if (obj.event === 'cDelete') {
            layer.confirm('确定彻底删除么？(将删除这些职位以及其下的所有账号)', function (index) {
                //开启loading
                const loading = layer.load(2);
                var paramBody = []
                paramBody[0] = data.uid;
                $.ajax({
                    url: '/position/cDelete',
                    method: "post",
                    contentType: 'application/json;charset=utf-8',
                    data: JSON.stringify(paramBody),
                    dataType: "json",
                    success: function (res) {
                        layer.close(loading);
                        if (res.code == 200) {
                            layer.alert("成功!");
                            obj.del();
                        } else {
                            layer.alert(res.msg);
                        }
                    }
                });
                layer.close(index);
            });
        }
    });
});

function validateCode() {
    var name = $("#name").val();
    if (name == null || name == "") {
        layer.alert("职位名称不能为空")
        return false;
    }
    return true;
}